package com.atguigu.algorithm;

import java.util.Arrays;

public class Printer {
    public static void main(String[] args) {
        int[][] array=new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}, {17, 18, 19, 20}, {21, 22, 23, 24}};
        System.out.println(Arrays.toString(clockwisePrint(array, array.length, array[0].length)));
        System.out.println(clockwisePrint(array,array.length,array[0].length).length);
    }
    public static int[] clockwisePrint(int[][] mat,int n,int m) {
        //n行m列
        int[] res = new int[n * m];
        //设定四个边界
        int left = 0;
        int right = m - 1;
        int up = 0;
        int down = n - 1;
        int i = 0;
        int x = left;
        int y = up;
        while (left<=right && up<=down) {
            //分别用四个小循环打印上右下左四条边
            //打印上边
            while (x <= right) {
                res[i++] = mat[y][x++];
            }
            up++;
            y += 1;
            x -= 1;
            //打印右边
            while (y <= down) {
                res[i++] = mat[y++][x];
            }
            right--;
            y -= 1;
            x-=1;
            //打印下边
            while (x >= left) {
                res[i++] = mat[y][x--];
            }
            down--;
            x += 1;
            y-=1;
            //打印左边
            while (y >= up) {
                res[i++] = mat[y--][x];
            }
            left++;
            y += 1;
            x+=1;
        }
        return res;
    }
}
